package com.skcc.cip.ngms.auth.processor;

// ~--- non-JDK imports --------------------------------------------------------

import java.util.Map;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import com.skcc.cip.security.SecurityConst;

public class MessageHeaderSetter implements Processor {
    public void process(Exchange exchange) throws BadCredentialsException {
	try {
	    Subject subject = (Subject) exchange.getIn().getHeader(Exchange.AUTHENTICATION); 
	    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) subject.getPrincipals().toArray()[0];
	    
	    Map<String, String> credentials = (Map) token.getCredentials();

	    String username = token.getName();

	    exchange.getIn().setHeader("authUser", username);
	    exchange.getIn().setHeader("authPassword", credentials.get(SecurityConst.KEY_PASSWORD));
	    exchange.getIn().setHeader("authHost", credentials.get(SecurityConst.KEY_NTLM_HOST));
	    exchange.getIn().setHeader("authDomain", credentials.get(SecurityConst.KEY_NTLM_DOMAIN));
	    
	    
	    HttpServletRequest request = exchange.getIn().getBody(HttpServletRequest.class);
	    HttpSession session=request.getSession(); 
	    Object companyCd=session.getAttribute("companyCD");
	    Object deptCode=session.getAttribute("deptCode");
	 
	    if(companyCd==null){
		companyCd="SKCC";
	    }
	    
	    if(deptCode==null){
		deptCode="RD10080";
	    }
	    exchange.getIn().setHeader("companyCD",(String)companyCd);
	    exchange.getIn().setHeader("deptCode",(String)deptCode);
	 
	} catch (Exception e) {
	    e.printStackTrace();
	    throw new BadCredentialsException("Authunitcation info is invalid");
	}

    }
}
